package com.neusoft.nep.SystemAdminstrator.Controller;

import com.neusoft.nep.common.FileUtils;
import com.neusoft.nep.entity.Feedback;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class Aqitrendtotalstatis {
    @FXML
    private Button btn_out;

    // 时间标签（与 FXML 中的 fx:id 对应）
    @FXML private Label time1, time2, time3, time4, time5, time6;
    @FXML private Label time7, time8, time9, time10, time11, time12;

    // 超标数量标签（与 FXML 中的 fx:id 对应）
    @FXML private Label count1, count2, count3, count4, count5, count6;
    @FXML private Label count7, count8, count9, count10, count11, count12;

    @FXML private MenuItem mi_PSL, mi_AQI, mi_PGC, mi_AqiDistribute, mi_Other, mi_AqiTrendTotal;

    // 日期格式化工具（支持多种格式兼容）
    private static final List<SimpleDateFormat> DATE_FORMATS = Arrays.asList(
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
            new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("yyyy/MM/dd"),
            new SimpleDateFormat("yyyyMMdd")
    );

    public void initialize() {
        // 初始化加载数据
        loadAqiTrendData();
    }

    @FXML
    public void updateAqiTrendCounts(ActionEvent event) {
        // 点击“刷新”时重新加载数据
        loadAqiTrendData();
    }

    /**
     * 核心方法：加载 AQI 超标趋势数据，包含“时间”和“超标数量”统计
     */
    private void loadAqiTrendData() {
        try {
            // 1. 获取所有网格员文件名
            List<String> officerFiles = getOfficerFileNames();
            List<Feedback> allFeedbacks = new ArrayList<>();

            // 2. 遍历每个网格员文件
            for (String fileName : officerFiles) {
                if (fileName.endsWith("back.txt")) {
                    // 读取文件中的反馈数据（Map结构）
                    Map<String, Feedback> feedbackMap = (Map<String, Feedback>)
                            FileUtils.readMapObject(fileName);

                    if (feedbackMap != null) {
                        allFeedbacks.addAll(feedbackMap.values());
                    }
                }
            }

            if (allFeedbacks.isEmpty()) {
                clearLabels(); // 无数据时清空表格
                return;
            }

            // 3. 提取有效数据并按时间排序
            List<Feedback> validFeedbacks = allFeedbacks.stream()
                    .filter(feedback -> feedback != null && feedback.getTime() != null)
                    .sorted(Comparator.comparing(this::parseTime)) // 按时间升序排序
                    .collect(Collectors.toList());

            // 4. 统计每月/每日超标数量（根据需求调整，这里示例按“月”统计）
            Map<String, Integer> monthlyOverlimit = countMonthlyOverlimit(validFeedbacks);

            // 5. 填充到界面（最多显示 12 条，可根据需求扩展）
            List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(monthlyOverlimit.entrySet());
            sortedEntries.sort(Map.Entry.comparingByKey()); // 按时间排序

            // 清空原有数据
            clearLabels();

            // 遍历填充前 12 条数据
            for (int i = 0; i < sortedEntries.size() && i < 12; i++) {
                Map.Entry<String, Integer> entry = sortedEntries.get(i);
                String time = entry.getKey();
                int count = entry.getValue();

                // 根据序号设置对应 Label
                Label timeLabel = getTimeLabel(i);
                Label countLabel = getCountLabel(i);

                if (timeLabel != null && countLabel != null) {
                    timeLabel.setText(time);
                    countLabel.setText(String.valueOf(count));
                }
            }

        } catch (Exception e) {
            // 异常处理：清空数据并打印日志
            clearLabels();
            e.printStackTrace();
        }
    }

    /**
     * 统计每月 AQI 超标数量（level 为三~六级）
     */
    private Map<String, Integer> countMonthlyOverlimit(List<Feedback> feedbacks) {
        Map<String, Integer> result = new TreeMap<>(); // TreeMap 自动按时间排序
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");

        for (Feedback feedback : feedbacks) {
            if (isOverlimitLevel(feedback.getAqiLevel())) { // 判断是否超标
                Date time = parseTime(feedback);
                String monthKey = monthFormat.format(time);

                // 累加计数
                result.put(monthKey, result.getOrDefault(monthKey, 0) + 1);
            }
        }
        return result;
    }

    /**
     * 判断 AQI 等级是否超标（三~六级为超标）
     */
    private boolean isOverlimitLevel(String level) {
        return level != null && (
                "三".equals(level) || "四".equals(level) ||
                        "五".equals(level) || "六".equals(level)
        );
    }

    /**
     * 解析时间字符串（兼容多种格式）
     */
    private Date parseTime(Feedback feedback) {
        String timeStr = feedback.getTime();
        for (SimpleDateFormat format : DATE_FORMATS) {
            try {
                return format.parse(timeStr);
            } catch (ParseException e) {
                // 尝试下一种格式
            }
        }
        // 所有格式都失败时，返回当前时间（避免崩溃）
        return new Date();
    }

    /**
     * 清空表格数据（时间和数量置空/置 0）
     */
    private void clearLabels() {
        // 时间标签置空
        Arrays.asList(time1, time2, time3, time4, time5, time6,
                        time7, time8, time9, time10, time11, time12)
                .forEach(label -> label.setText(""));

        // 数量标签置 0
        Arrays.asList(count1, count2, count3, count4, count5, count6,
                        count7, count8, count9, count10, count11, count12)
                .forEach(label -> label.setText("0"));
    }

    /**
     * 根据序号获取对应的“时间” Label
     */
    private Label getTimeLabel(int index) {
        List<Label> timeLabels = Arrays.asList(time1, time2, time3, time4, time5, time6,
                time7, time8, time9, time10, time11, time12);
        return index < timeLabels.size() ? timeLabels.get(index) : null;
    }

    /**
     * 根据序号获取对应的“超标数量” Label
     */
    private Label getCountLabel(int index) {
        List<Label> countLabels = Arrays.asList(count1, count2, count3, count4, count5, count6,
                count7, count8, count9, count10, count11, count12);
        return index < countLabels.size() ? countLabels.get(index) : null;
    }

    /**
     * 获取所有网格员文件（girdxxxback.txt）
     */
    private List<String> getOfficerFileNames() {
        List<String> fileNames = new ArrayList<>();
        File directory = new File("."); // 当前工作目录
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().startsWith("gird") &&
                        file.getName().endsWith("back.txt")) {
                    fileNames.add(file.getName());
                }
            }
        }
        return fileNames;
    }

    public void OUT(ActionEvent actionEvent) {
        System.exit(0);
    }

    public void PSLClick(ActionEvent event) throws IOException {
        loadFXML("../View/publicList.fxml");
    }

    public void AQIListClick(ActionEvent event) throws IOException {
        loadFXML("../View/AQImakesure.fxml");
    }

    public void PGCClick(ActionEvent event) throws IOException {
        loadFXML("../View/ProvincialGroupComponentItemInspectionStatistics.fxml");
    }

    public void AqiDistributeClick(ActionEvent event) throws IOException {
        loadFXML("../View/AqiDistributeTotalStatisView.fxml");
    }

    public void OtherClick(ActionEvent event) throws IOException {
        loadFXML("../View/OtherTotalStatisView.fxml");
    }

    public void AqiTrendClick(ActionEvent event) throws IOException {
        loadFXML("../View/AqiTrendTotalStatisView.fxml");
    }

    private void loadFXML(String fxmlPath) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource(fxmlPath);
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }
}